package nl.mkmedia.tuio {
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.DataEvent;
	import flash.net.XMLSocket;
	
	/**
	 * @author Mingoes Kukupessy (mingoes at gmail dot com)
	 */
	public class TUIOSocket {
		
		private var _socket:XMLSocket;
		private var _aliveCallback:Function;
		private var _setCallback:Function;
		
		/**
		 * TODO: Use EnterFrame
		 */
		public function TUIOSocket(host:String, port:int, aliveCallback:Function, setCallback:Function)
		{
			_socket = new XMLSocket();
			_socket.addEventListener(Event.CONNECT, onConnect);
			_socket.addEventListener(DataEvent.DATA, socketData);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
			_socket.connect(host, port);
			_aliveCallback = aliveCallback;
			_setCallback = setCallback;
		}

		private function socketData(event : DataEvent) : void 
		{
			var xml:XML = new XML(event.data);
			for each(var msg:XML in xml.MESSAGE){
				parseMessage(msg);
			}
		}
		
		private function parseMessage(msg:XML):void
		{
			var type:String = msg.ARGUMENT[0].@VALUE;
			switch(type){
				case 'alive':
						var points:Array = new Array();
						for(var i:int = 1; i < msg.ARGUMENT.length(); i++){
							points.push(msg.ARGUMENT[i].@VALUE);
						}
						_aliveCallback(points);
					break;
				case 'set':
					_setCallback(msg.ARGUMENT[1].@VALUE, msg.ARGUMENT[2].@VALUE, msg.ARGUMENT[3].@VALUE);
					break;
			}
		}
		
		private function onError(event : IOErrorEvent) : void 
		{
			t('Connection error');
		}
		
		private function t(msg:*):void
		{
			trace('[TUIO Socket] '+msg);
		}
		
		private function onConnect(event : Event) : void 
		{
			t('Connected');
		}
	}
}
